/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import facades.PasswordRecoveryFacade;
import facades.UserFacade;
import entities.PasswordRecovery;
import entities.User;
import util.Sha256Encrypter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Event;
import javax.inject.Named;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.context.RequestContext;
import qualifiers.CreatedEntityEvent;
import qualifiers.RecoveredPasswordEvent;

/**
 *
 * @author damfercer
 */
@Named(value = "recoveryPasswordBean")
@SessionScoped
public class RecoveryPasswordBean implements Serializable{
    @ManagedProperty(value="#{param.id}")
    private Integer recoverId;
    @Inject
    private UserFacade userFacade;
    @Inject
    private PasswordRecoveryFacade prFacade;
    private String email;
    private String newPassword;
    @Inject
    @RecoveredPasswordEvent
    Event<User> recoveredEvent;
    @Inject
    @CreatedEntityEvent
    Event<PasswordRecovery> newRecoveryEvent;
    /**
     * Creates a new instance of RecoveryPasswordBean
     */
    public RecoveryPasswordBean() {
        email=new String();
    }
    
    public void reinitEmail(){
        this.email=new String();
    }
    
    public void createRecovery(){
        FacesContext context=FacesContext.getCurrentInstance();
        HttpServletRequest request=(HttpServletRequest)context.getExternalContext().getRequest();
        Locale locale=context.getViewRoot().getLocale();
        ResourceBundle rb=ResourceBundle.getBundle("messages",locale);
        User user=userFacade.getUserFromEmail(email);
        if(user==null){
            String emailError=rb.getString("EmailPattern");
            FacesMessage message =new FacesMessage(emailError, emailError);
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, message); 
            context.renderResponse();
        }
        else{
            PasswordRecovery pr=new PasswordRecovery();
            Date now=new Date();
            Calendar cal=Calendar.getInstance();
            cal.setTime(now);
            cal.add(Calendar.HOUR, 1);
            pr.setExpeditonDate(now);
            pr.setUser(user);
            pr.setLimitDate(cal.getTime());
            pr.setValid(true);
            prFacade.create(pr);
            newRecoveryEvent.fire(pr);
            String recoverSent=rb.getString("RecoverSent");
            FacesMessage message =new FacesMessage(recoverSent, recoverSent);
            message.setSeverity(FacesMessage.SEVERITY_INFO);
            context.addMessage(null, message); 
            context.renderResponse();
            RequestContext requestContext=RequestContext.getCurrentInstance();
            requestContext.execute("passwordRecoveryDialog.hide();");
        }
    }
    
    public String changePassword(){
        String action=null;
        FacesContext context=FacesContext.getCurrentInstance();
        Locale locale=context.getViewRoot().getLocale();
        ResourceBundle rb=ResourceBundle.getBundle("messages",locale);
        if(getRecoverId()!=null){
            action="/views/recover/Recover?id="+recoverId;
            Date now=new Date();
            PasswordRecovery pr=prFacade.find(getRecoverId());
            if(pr==null){
                String emailError=rb.getString("RecoverNoExists");
                FacesMessage message =new FacesMessage(emailError, emailError);
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                context.addMessage(null, message); 
                context.renderResponse();
            }
            else{
                if(!pr.getUser().getEmail().equals(email)){
                    String emailError=rb.getString("RecoverNoExists");
                    FacesMessage message =new FacesMessage(emailError, emailError);
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    context.addMessage(null, message); 
                    context.renderResponse();
                }
                else if(!pr.getValid()){
                    String emailError=rb.getString("RecoveryExpired");
                    FacesMessage message =new FacesMessage(emailError, emailError);
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    context.addMessage(null, message); 
                    context.renderResponse();
                }
                else if(now.compareTo(pr.getLimitDate())>0){
                    String emailError=rb.getString("RecoveryExpired");
                    FacesMessage message =new FacesMessage(emailError, emailError);
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    context.addMessage(null, message); 
                    context.renderResponse();
                }
                else{
                    try {
                        String hashedString=Sha256Encrypter.getSha256(newPassword);
                        pr.getUser().setPassword(hashedString);
                        userFacade.edit(pr.getUser());
                        //pr.getUser().setPassword(newPassword);
                        pr.setValid(false);
                        prFacade.edit(pr);
                        recoveredEvent.fire(pr.getUser());
                        action="/views/candidate/NewEditCandidateView?faces-redirect=true";

                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(RecoveryPasswordBean.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (UnsupportedEncodingException ex) {
                        Logger.getLogger(RecoveryPasswordBean.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
        else{
           String emailError=rb.getString("RecoverNoExists");
            FacesMessage message =new FacesMessage(emailError, emailError);
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, message); 
            context.renderResponse(); 
        }
        return action;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the newPassword
     */
    public String getNewPassword() {
        return newPassword;
    }

    /**
     * @param newPassword the newPassword to set
     */
    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    /**
     * @return the recoverId
     */
    public Integer getRecoverId() {
        return recoverId;
    }

    /**
     * @param recoverId the recoverId to set
     */
    public void setRecoverId(Integer recoverId) {
        this.recoverId = recoverId;
    }
}
